package com.wonders.module.auth.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wonders.common.constant.CommonConstant;
import com.wonders.common.constant.TipConstant;
import com.wonders.framework.entity.vo.Page;
import com.wonders.framework.exception.BusinessException;
import com.wonders.framework.util.ValidateUtil;
import com.wonders.framework.util.bean.BeanUtil;
import com.wonders.module.auth.dao.RoleAuthDao;
import com.wonders.module.auth.dao.RoleDao;
import com.wonders.module.auth.dao.UserRoleDao;
import com.wonders.module.auth.entity.bo.Role;
import com.wonders.module.auth.entity.vo.RoleVo;
import com.wonders.module.auth.service.RoleService;

/**
 * 角色业务层实现
 * 
 * @author WuBin
 * 
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private UserRoleDao userRoleDao;

	@Autowired
	private RoleAuthDao roleAuthDao;

	public Page query(RoleVo roleVo, Page page) {
		page = roleDao.query(roleVo, page);
		return BeanUtil.copyPage(page, RoleVo.class);
	}

	public void save(RoleVo roleVo) {
		validate(roleVo, CommonConstant.Action.ADD);
		Role role = BeanUtil.copyProperties(roleVo, Role.class);
		role.setEnable(CommonConstant.Status.ENABLED);
		roleDao.save(role);
	}

	public RoleVo load(Long id) {
		Role role = roleDao.get(Role.class, id);
		if (role == null) {
			throw new BusinessException(TipConstant.DATA.NOT_FOUND);
		}
		return BeanUtil.copyProperties(role, RoleVo.class);
	}

	public void update(RoleVo roleVo) {
		validate(roleVo, CommonConstant.Action.EDIT);
		Role role = roleDao.get(Role.class, roleVo.getId());
		if (role == null) {
			throw new BusinessException(TipConstant.DATA.NOT_FOUND);
		}
		BeanUtil.copyProperties(roleVo, role, "enable");
		roleDao.update(role);
	}

	public void remove(List<Long> keys) {
		roleDao.remove(keys);
		userRoleDao.removeUserRoleByRoles(keys);
		roleAuthDao.removeByRoles(keys);
	}

	public void validate(RoleVo roleVo, String action) {
		if (!ValidateUtil.nullCheck(roleVo, "code", "name")) {
			throw new BusinessException(TipConstant.PARAM.MISSING);
		}
		if (CommonConstant.Action.EDIT.equals(action)
				&& !ValidateUtil.nullCheck(roleVo, "id")) {
			throw new BusinessException(TipConstant.PARAM.MISSING);
		}
		if (!ValidateUtil.isLetterAndNumber(roleVo.getCode())
				|| !ValidateUtil.maxLengthCheck(roleVo.getCode(), 25)) {
			throw new BusinessException("代码" + TipConstant.PARAM.FORMAT_ERROR);
		}
		if (!ValidateUtil.maxLengthCheck(roleVo.getName(), 25)) {
			throw new BusinessException("名称" + TipConstant.PARAM.FORMAT_ERROR);
		}
		List<Map<String, Object>> existList = roleDao.isExist(roleVo);
		if (existList != null && existList.size() > 0) {
			String key = (String) existList.get(0).get("key");
			throw new BusinessException(key + TipConstant.DATA.EXIST);
		}
	}

}
